//
//  SideMenuViewController.swift
//  WCHBLEApp
//
//  Created by 娟华 胡 on 2021/3/18.
//


import UIKit
import XappKit
import XappBase
import SnapKit
import MessageUI

typealias SideMenuHandler = (() -> Void)

private let animationDuration: TimeInterval = 0.3
private let selectedCheckboxImage = UIImage(named: "selectedCheckbox")
private let defaultCheckboxImage = UIImage(named: "defaultCheckbox")

class SideMenuViewController: MH_VC_BaseViewController {
    
    var sideMenuDidHide: SideMenuHandler?
    private var navgation:UINavigationController?
    public var sendEmail:(()->Void)?
    
    @IBOutlet weak var shadowView: UIView!
    @IBOutlet weak var menuTableView: UITableView!
    @IBOutlet weak var menuTableViewWidthConstraint: NSLayoutConstraint!
    
    
    fileprivate var menuItems = ["隐私政策", "反馈和建议", "关于我们", "联系我们"]

    // MARK: - Lifecycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        menuTableView.isHidden = true
        menuTableView.delegate = self
        menuTableView.dataSource = self
        view.isHidden = true
        menuTableViewWidthConstraint.constant = UIScreen.main.bounds.width * 0.7
        setupGestureRecognizers()
        setTableHeadView()
    }
    
    // MARK: - Public functions
    
    func showSideMenu(viewController: UIViewController, currentNav: UINavigationController, sideMenuDidHide: SideMenuHandler?) {
        self.sideMenuDidHide = sideMenuDidHide
        self.navgation = currentNav
        modalPresentationStyle = .overCurrentContext
        let size = view.frame.size
        
        viewController.present(self, animated: false) { [weak self] in
            self?.view.isHidden = false
            self?.menuTableView.frame.origin = CGPoint(x: -size.width, y: 0)
            UIView.animate(
                withDuration: animationDuration,
                animations: {
                    self?.view.backgroundColor = UIColor.black.withAlphaComponent(0.63)
                    self?.slideAnimationToPoint(.zero)
                    self?.menuTableView.isHidden = false
                }
            )
        }
    }
    
    // MARK: - Private functions
    @IBAction func shadowGetureAction(_ sender: Any) {
            dismissSideMenu()
    }
    
    fileprivate func setupGestureRecognizers() {
        let dissmisSideMenuSelector = #selector(SideMenuViewController.dismissSideMenu)
        
//        let tapRecognizer = UITapGestureRecognizer(target: self, action: dissmisSideMenuSelector)
//        tapRecognizer.delegate = self
//        shadowView.addGestureRecognizer(tapRecognizer)
        
        let swipeRecognizer = UISwipeGestureRecognizer(target: self, action: dissmisSideMenuSelector)
        swipeRecognizer.direction = .left
        swipeRecognizer.delegate = self
        view.addGestureRecognizer(swipeRecognizer)
    }
    
    fileprivate func didSelectItem(at indexPath: IndexPath) {
     
        dismissSideMenu()
    }
    
    @objc fileprivate func dismissSideMenu() {
        let size = view.frame.size
        
        UIView.animate(
            withDuration: animationDuration,
            animations: {
                self.slideAnimationToPoint(CGPoint(x: -size.width, y: 0))
                self.view.backgroundColor = .clear
            },
            completion: { _ in
                self.view.isHidden = true
                self.menuTableView.isHidden = true
                self.sideMenuDidHide?()
            }
        )
    }
    
    fileprivate func slideAnimationToPoint(_ point: CGPoint) {
        UIView.animate(withDuration: animationDuration) {
            self.menuTableView.frame.origin = point
        }
    }
    
    
    fileprivate func setTableHeadView() {
        let headView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 200))
        let meunHeadView = SideMeunHeadView.instanceFromNib()
        headView.addSubview(meunHeadView!)
        meunHeadView?.snp.makeConstraints({ (make) in
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.bottom.equalTo(0)
        })
        self.menuTableView.tableHeaderView = headView
    }
    
}

extension SideMenuViewController: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return menuItems.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
        if (cell == nil) {
            cell = UITableViewCell()
        }

        cell?.textLabel?.text = menuItems[indexPath.row]
        cell?.textLabel?.font = UIFont.systemFont(ofSize: 15.0)
        
        if (indexPath.row == 0) {
            cell?.imageView?.image = UIImage.init(named: "private")
        }else if (indexPath.row == 1) {
            cell?.imageView?.image = UIImage.init(named: "feedback")
        }else if (indexPath.row == 2) {
            cell?.imageView?.image = UIImage.init(named: "aboutus")
        }else if (indexPath.row == 3) {
            cell?.imageView?.image = UIImage.init(named: "concatus")
        }
        
        return cell ?? UITableViewCell()
    }
    
}

extension SideMenuViewController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let size = view.frame.size
        
        UIView.animate(
            withDuration: animationDuration,
            animations: {
                self.slideAnimationToPoint(CGPoint(x: -size.width, y: 0))
                self.view.backgroundColor = .clear
            },
            completion: { _ in
                self.view.isHidden = true
                self.menuTableView.isHidden = true
                self.sideMenuDidHide?()
             
                if (indexPath.row == 0) {
                    
                    let webVC = PrivateWebViewController.init(nibName: "PrivateWebViewController", bundle: Bundle.main)
                    self.navgation?.pushViewController(webVC, animated: true)
                
                }else if (indexPath.row == 1) {
                    self.sendEmail?()
    
                }else if (indexPath.row == 2) {
                    let webVC = MH_VC_WebController.init()
                    webVC.url = "http://www.wch.cn/about_us.html"
                    self.navgation?.pushViewController(webVC, animated: true)
                }else if (indexPath.row == 3) {
                    let webVC = MH_VC_WebController.init()
                    webVC.url = "http://www.wch.cn/contact_us.html"
                    self.navgation?.pushViewController(webVC, animated: true)
                }
                
            }
        )
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
}

extension SideMenuViewController: UIGestureRecognizerDelegate {
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
    
}



